package me.seu.demo.controller;

import lombok.extern.slf4j.Slf4j;
import me.seu.demo.entity.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * ES 索引、映射 API
 *
 * docker 9300 未暴露
 *
 * @author liangfeihu
 * @since 2020/4/22 18:31
 */
@Slf4j
@RestController
@RequestMapping("/es")
public class EsOperationController {

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    @GetMapping("/index/create")
    public ResponseEntity createEsIndex() {
        // 创建索引，会根据Item类的@Document注解信息来创建
        boolean index = elasticsearchTemplate.createIndex(Item.class);
        log.info("[elasticsearchTemplate.createIndex(Item.class)] return flag={}", index);

        return ResponseEntity.ok("create elasticsearch index success");
    }

    @GetMapping("/mapping/create")
    public ResponseEntity createEsMapping() {
        // 配置映射，会根据Item类中的id、Field等字段来自动完成映射
        boolean flag = elasticsearchTemplate.putMapping(Item.class);
        log.info("[elasticsearchTemplate.putMapping(Item.class)] return flag={}", flag);

        return ResponseEntity.ok("create elasticsearch mapping success");
    }


    @GetMapping("/index/delete")
    public ResponseEntity deleteEsIndex() {

        boolean flag = elasticsearchTemplate.deleteIndex(Item.class);
        log.info("[elasticsearchTemplate.deleteIndex(Item.class)] return flag={}", flag);

        // 根据索引名字删除
        elasticsearchTemplate.deleteIndex("item");

        return ResponseEntity.ok("delete elasticsearch index success");
    }

}
